<?php

namespace app\controllers;

use app\common\Common;
use app\common\utils\http\HttpClientBuilder;
use Yii;
use yii\web\Controller;
use yii\web\Response;


class ApiController extends Controller
{
    /**
     * @var \Redis $redis
     */
    protected $redis = null;

    /**
     * @var string
     */
    protected string $accessToken;

    /**
     * @var array
     */
    protected array $requestParams = [];

    /**
     * @param $action
     * @return bool
     * @throws \yii\web\BadRequestHttpException
     */
    public function beforeAction($action): bool
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $this->setAccessToken();

        return parent::beforeAction($action);
    }

    /**
     * @param $action
     * @param $result
     * @return mixed
     */
    public function afterAction($action, $result)
    {
        return parent::afterAction($action, $result);
    }

    /**
     * @return mixed|object|\Redis|null
     */
    protected function getRedis()
    {
        if ($this->redis === null) {
            $this->redis = Yii::$app->redis;
        }

        return $this->redis;
    }

    /**
     * 设置请求参数
     */
    protected function setRequestParams()
    {
        $this->requestParams = Common::getRequestParams();
    }

    /**
     * 获取参数
     *
     * @param $key
     * @param null $default
     * @return mixed|null
     */
    protected function getRequestParams($key, $default = null)
    {
        return $this->requestParams[$key] ?? $default;
    }

    /**
     * @return void
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \RedisException
     */
    protected function setAccessToken()
    {
        $redis = self::getRedis();
        $key = 'access_token';
        $accessToken = $redis->get($key);
        if (!$accessToken) {
            $wechat = \Yii::$app->params['wechat'];
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $wechat['appid'] . '&secret=' . $wechat['secret'];
            $result = HttpClientBuilder::newBuilder('wechat')->timeout(60)->create()->get($url)->getBody();
            $_result = json_decode($result, true);
            $accessToken = $_result['access_token'] ?? '';
            $expiresIn = $_result['expires_in'] ?? '';
            $redis->setnx($key, $accessToken);
            $redis->expire($key, $expiresIn);
        }
        $this->accessToken = $accessToken;
    }

    /**
     * 正确返回
     *
     * @param array $data
     * @param int $code
     * @param string $msg
     * @return array
     */
    protected function jsonSuccess(array $data = [], int $code = 0, string $msg = ''): array
    {
        return Yii::$app->response->data = ['code' => $code, 'data' => $data, 'message' => $msg];
    }

    /**
     * 失败返回
     *
     * @param string $msg
     * @param int $code
     * @param array $data
     * @return array
     */
    protected function jsonFail(string $msg = '', int $code = 1, array $data = []): array
    {
        $code = $code ?: 1;

        return Yii::$app->response->data = ['code' => $code, 'data' => $data, 'message' => $msg];
    }

    /**
     * 自定义类型返回
     *
     * @param mixed $data
     * @param int $code
     * @param string $msg
     * @return array
     */
    protected function jsonResponse($data, int $code = 0, string $msg = ''): array
    {
        return Yii::$app->response->data = ['code' => $code, 'data' => $data, 'message' => $msg];
    }
}